package com.learn.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;

/**
 * @author DJJ_F
 * @version 1.0
 * @date 2025/02/18
 * @description 获取SqlSession的工具类
 * SqlSessionFactoryBuilder 的最佳作用域是方法的局部变量
 * SqlSessionFactory的最佳作用域 一个应用域，一个数据库一个
 * SqlSession的最佳作用域 请求或方法作用域，一个线程对应一个
 */
public class SqlSessionUtil {
    // ThreadLocal的知识参考javaweb
    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<>();

    // 私有化构造方法防止，外部创建类
    private SqlSessionUtil() {
    }

    // 因为一个sqlSessionFactory对应一个数据库，所以只用创建一个对象
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static SqlSession openSession() {
        SqlSession sqlSession = threadLocal.get();
        if (sqlSession == null) {
            sqlSession = sqlSessionFactory.openSession();
            threadLocal.set(sqlSession);
        }
        return sqlSession;
    }
    public static void close() {
        SqlSession sqlSession = threadLocal.get();
        if (sqlSession != null) {
            sqlSession.close();
            threadLocal.remove();
        }
    }
}
